<template>
  <VPage>
    <VTable ref="tableRef" v-bind="tableOptins">
      <template #form="{ form }">
        <XForm ref="form" :fieldList="fieldList" :options="formOption" :formData="form" :originOption="originOption" v-if="formShow" />
      </template>
      <template #toolbar_btns>
        <VButton auth="/pmc/base/asinFollow/enable" @click="handleStatus(1)">
          <VStatus :value="true" />
        </VButton>
        <VButton auth="/pmc/base/asinFollow/disable" @click="handleStatus(0)">
          <VStatus :value="false" />
        </VButton>

        <VButton auth="/pmc/base/asinFollow/add" type="primary" @click="openEdit('add')"> 新增 </VButton>

        <VButton auth="/pmc/base/asinFollow/import" icon="Download" class="ml-auto" @click="onImport"> 导入 </VButton>
        <VButton auth="/pmc/base/asinFollow/export" @click="onExport"> <svg-icon icon-class="import" class="mr-[4px]" /> 导出 </VButton>

        <!-- <el-button @click="handleStatus(1)">
          <div class="dk-iconfont icon-CircleCheck text-[#3487FF]" />
          启用
        </el-button>
        <el-button @click="handleStatus(0)"><svg-icon icon-class="state_disabled" class="text-[red] mr-[4px]" />禁用</el-button>

        <el-button type="primary" @click="openEdit('add')"> 新增 </el-button>
        <el-button icon="Download" class="ml-auto" @click="onImport"> 导入 </el-button>
        <el-button @click="onExport">
          <span class="flex items-center"> <svg-icon icon-class="import" class="mr-[4px]" /> 导出 </span>
        </el-button> -->
      </template>

      <!-- 关联副店铺 -->
      <template #SubStoreName="{ row }">
        <template v-for="(item, i) in row.base_follow_asin_relation" :key="i">
          <VText :value="item.base_asin_list.store_name" :line="1" v-if="i < 2" />
        </template>
        <el-popover placement="left" :width="200" trigger="click" v-if="row.base_follow_asin_relation.length > 2">
          <div>
            <VText v-for="(item, i) in row.base_follow_asin_relation" :key="i" :value="item.base_asin_list.store_name" :line="1" />
          </div>
          <template #reference>
            <el-link type="primary" :underline="false">查看更多</el-link>
          </template>
        </el-popover>
      </template>
    </VTable>

    <!-- 详情 -->
    <Details ref="DetailsRef" />
    <!-- 日志 -->
    <XLog ref="logRef" :api="followLog"></XLog>

    <!-- 导入 -->
    <DialogImport v-model:modelValue="visibleImport" :downloadApi="downloadImportTpl" downloadName="跟卖ASIN" :api="followSaleImport" @refresh="query" />
    <!-- 导出中心 -->
    <DerivedCenter ref="DerivedCenterRef"></DerivedCenter>
  </VPage>
</template>

<script setup lang="jsx">
import { list, updateStatus, followLog, downloadImportTpl, followSaleImport } from "./api.js"

import { ElMessage, ElMessageBox } from "element-plus"
import { onMounted, ref, toRefs } from "vue"
import XForm from "@/components/XForm/index.vue"

// 详情
import Details from "./components/Details/index.vue"
const DetailsRef = ref()
// 日志
import XLog from "@/components/XLog"
const logRef = ref()

// 导入
import DialogImport from "@/components/DialogImport/index.vue"
const visibleImport = ref(false)
// const downloadUrl = ref("")
const onImport = async () => {
  visibleImport.value = true
}
// 导出中心
import DerivedCenter from "@/components/DerivedCenter"
const DerivedCenterRef = ref()
const onExport = () => {
  let rows = tableRef?.value.$table.getCheckboxRecords()
  let formData = tableRef?.value?.getQueryForm()
  let condition = {}
  if (rows?.length) {
    condition.id = rows.map((v) => v.id)
  } else {
    condition = formData
  }
  DerivedCenterRef.value.open({
    tag_name: "FOLLOW_SALE_LIST",
    condition,
  })
}

const tableRef = ref()

const openEdit = (type, row) => {
  DetailsRef.value.open(type, row)
}

// 获取已选中的行
const getSelectRow = () => {
  const getCheckboxRecords = tableRef?.value.$table.getCheckboxRecords()
  if (!getCheckboxRecords.length) {
    ElMessage({ showClose: true, message: "请至少选择一条数据！", type: "warning" })
    return false
  }
  const arr = []
  getCheckboxRecords.map((e) => {
    arr.push(e.id)
  })
  return arr
}

// 启用
const handleStatus = (status, row = {}) => {
  let ids = []
  if (!row.id) {
    ids = getSelectRow()
    if (!ids.length) {
      return false
    }
  } else {
    ids = [row.id]
  }

  ElMessageBox.confirm(`此操作将 ${status ? "启用" : "禁用"} ${ids.length}条数据, 是否继续?`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
    confirmButtonClass: "oms-message-confirm-button",
  }).then(async () => {
    try {
      let params = {
        follow_sale_id: ids,
        status,
      }
      updateStatus(params).then((res) => {
        ElMessage.success("操作成功")
        query()
      })
    } catch (e) {
      throw Error(e)
    }
  })
}
// 查询
const query = () => {
  tableRef?.value.query()
}
// 枚举 数据
const originOption = ref({})

import {
  fieldList, // 搜索条件 配置
  tableColumns, // 列配置
} from "./config.jsx"
const formShow = ref(false)
//获取下拉数据
onMounted(async () => {
  await getOption()
  nextTick(() => (formShow.value = true))
})

import { getEnum, getAmazonSite } from "@/utils/enumUtils"
const getOption = async () => {
  originOption.value.amazonSite = (await getAmazonSite()).map((v) => ({ label: v.label, value: v.label }))

  // downloadUrl.value = (await downloadImportTpl()).data
}

const formOption = ref({ inline: true })

// 列表配置
const tableOptins = reactive({
  formConfig: {
    data: {
      site_code: [],
      skuRange: { type: "sku", value: "" },
      asinRange: { type: "asin", value: "" },
      storeRange: { type: "store_id", value: "" },
      userRange: { type: "operator_user", value: "" },
      timeRange: { type: "created_at", value: "", range: true },
    },
  },
  rowConfig: { keyField: "id", height: 80 },
  showOverflow: false,
  columns: [],
  proxyConfig: {
    ajax: {
      query: async ({ page, form }) => {
        let params = {
          page: page.pageNum,
          page_size: page.pageSize,
          ...initForm(form),
        }
        let res = await list(params)
        return res
      },
    },
  },
})
const handleColumn = {
  title: "操作",
  width: 180,
  fixed: "right",
  slots: {
    default: ({ row }) => {
      return [
        <div>
          <el-button link type="primary" onClick={() => openEdit("edit", row)}>
            编辑
          </el-button>
          {row.status_text == "禁用" ? (
            <el-button link type="primary" onClick={() => handleStatus(1, row)}>
              启用
            </el-button>
          ) : (
            <el-button link type="danger" onClick={() => handleStatus(0, row)}>
              禁用
            </el-button>
          )}
          <el-button link type="primary" onClick={() => logRef?.value.open({ id: row.id }, true)}>
            日志
          </el-button>
        </div>,
      ]
    },
  },
}
tableOptins.columns = [{ type: "checkbox", fixed: "left", width: 40 }, ...tableColumns.value, handleColumn]

const initForm = (form) => {
  let keys = ["sku", "asin", "store_id", "follow_store_id"]
  keys.forEach((key) => {
    form[key] = form[key]?.split("\n")?.filter((v) => !!v.trim())
    form[key] = form[key]?.map((v) => v.trim())
  })
  return form
}
</script>
<style lang="scss" scoped></style>
